//
//  HotViewcontroller.m
//  YSBEmployer
//
//  Created by developer on 2021/12/05.
//  Copyright © 2021 ysb. All rights reserved.
//

#import "YSBJobChatWebSocketManager.h"


#import "YSBHomeController.h"

#import "InterfaceSwitchingLogic.h"

#import "YSBPermanentWorkerHomeController.h"


#import "HttpClient.h"


@implementation HttpClient

#pragma mark - 修改升级功能,去除请求苹果官网
- (void)updateMethodWithStrive:(BOOL)needStrive andUpdateContent:(NSArray *)updateContentArray andUpdateModel:(UpdateModel *)model {
    
    //获取服务器上应用的最新版本号
    NSString *updateVersion = [YSBCommonTool isBlankString:model.version_no] ? @"" : model.version_no;
    
    NSDictionary *info= [[NSBundle mainBundle] infoDictionary];
    NSString *bundleVersion = [YSBCommonTool isBlankString:info[@"CFBundleShortVersionString"]] ? @"" : info[@"CFBundleShortVersionString"];
    
    NSString *messageStr = [NSString stringWithFormat:@"发现新版本(%@),是否更新?", updateVersion];
    if (updateContentArray.count > 0) {
        NSString *updateStr = @"";
        if (updateContentArray.count > 1) {
            updateStr = [updateContentArray componentsJoinedByString:@" \n"];
        }else{
            updateStr = updateContentArray[0];
        }
        messageStr = updateStr;
    }
    
    if ([updateVersion isEqualToString:bundleVersion]) {
        //            GSToastInCenter(@"当前版本为最新版本无需更新！");
    }
    else {
        if (self.updateAlert == nil) {
            self.updateAlert = [SELUpdateAlert showUpdateAlertWithVersion:updateVersion Description:messageStr isForcingUpdate:needStrive];
            self.updateAlert.hidden = YES;
            //添加弹框界面
            if (self.updateAlert) {
                self.updateAlert.tag = 1;
                [[YSBMSAlertManager shareManager] addAlert:self.updateAlert];
            }
        }
    }
    
}


@end



@implementation YSBJobChatWebSocketManager


- (void)getJobChatListWithStartIndex:(NSInteger)startIndex andSearchName:(NSString *)searchName {
    
    NSDictionary *numDict = @{
        @"start":@(startIndex),
    };
    if (searchName.length > 0) {//搜索姓名传值
        numDict = @{
            @"start" : @(startIndex),
            @"real_name" : searchName,
        };
    }
    
    NSDictionary *data = @{
        @"msg_source":@"recruit",//来源recruit招聘板块
        @"sign":@"employer",//发送者类型
        @"msg_type":@"chat_list",//消息类型
        @"content":numDict,
    };
    [self sendDataToServer:data];
    
}


//处理相应执行方法
- (void)msgToGoWithDict:(NSDictionary *)dict {
    
    if (![YSBCommonTool isBlankString:dict[@"status"]]) {//获取状态
        
        NSString *status = dict[@"status"];
        
        if ([status isEqualToString:@"bind_success"]) {
            NSLog(@"求职聊天绑定成功");
        }
        else if ([status isEqualToString:@"bind_fail"]) {
            NSLog(@"求职聊天绑定失败");
        }
        else if ([status isEqualToString:@"send_un_forbid_invite_forbid"]) {
            NSLog(@"求职聊天可以聊天但是不能邀请");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshJobChatRoomMessageNotification" object:dict];

        }
        else if ([status isEqualToString:@"send_forbid"]) {
            NSLog(@"求职聊天禁止发送");
            if ([dict[@"content"] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *contentDict = dict[@"content"];
                NSString *msg_type = contentDict[@"msg_type"];
                NSString *ID = contentDict[@"from"];
                NSString *msg = contentDict[@"msg"];
                
                //收到文本的求职聊天消息
                if ([msg_type isEqualToString:@"text"] ||
                    [msg_type isEqualToString:@"grey"]) {
                    NSLog(@"求职聊天禁言进入text或grey");
                    if (![msg containsString:@"首次沟通未回应"]) {
                        [self saveTextMsgForbidWithDict:contentDict andStatus:status];
                    }
                    [self saveReplyModelWithIsSendForbid:YES andEmployeeID:ID andMsg:msg];
                    
                    if (![[YSBCommonTool getCurrentVC] isKindOfClass:[YSBJobChatVC class]]) {
                        [self getJobChatListWithStartIndex:0 andSearchName:@""];
                    }
                }
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshJobChatRoomMessageNotification" object:dict];

        }
        else if ([status isEqualToString:@"success"]) {
            NSLog(@"求职聊天系统心跳Ping返回成功");
        }
        else if ([status isEqualToString:@"system_success"] ||
                 [status isEqualToString:@"send_un_forbid"] ) {
            NSLog(@"求职聊天系统返回消息成功");
            if ([dict[@"content"] isKindOfClass:[NSString class]]) {//判断是否字符串
                YSBToastInCenter(dict[@"content"]);
            }
            if ([dict[@"content"] isKindOfClass:[NSDictionary class]]) {//判断是否字典
                NSLog(@"求职聊天进入content");

                NSDictionary *contentDict = dict[@"content"];
                if (![YSBCommonTool isBlankString:contentDict[@"msg_type"]]) {
                    NSLog(@"求职聊天进入msg_type");
                    //msg_type : text文本消息  invite招聘邀请  reply沟通确认 chat_list聊天列表 grey 禁止聊天
                    NSString *msg_type = contentDict[@"msg_type"];
                    
                    //1.求职消息聊天列表
                    if ([msg_type isEqualToString:@"chat_list"]) {
                        NSLog(@"求职聊天进入chat_list");
                        
                        YSBJobChatListModel *jobChatListModel = [YSBJobChatListModel yy_modelWithJSON:contentDict];
                        
                        NSLog(@"求职聊天进入chat_list,msg_type = %@",jobChatListModel.msg_type);
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshJobChatMessageNotification" object:jobChatListModel];
                        
                        //本地保存
                        [self saveJobChatListWithModel:jobChatListModel];
                        
                        if (jobChatListModel.all_un_read_number > 0) {
                            //设置底部图标未读求职消息数
                            [self showTabBarItemNum];
                        }
                        
                    }
                    
                    //2.收到单个用户在求职聊天消息
                    if ([msg_type isEqualToString:@"text"]) {
                        NSLog(@"求职聊天进入text");
                        YSBJobChatModel *jobChatModel = [YSBJobChatModel yy_modelWithJSON:contentDict];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshJobChatRoomMessageNotification" object:jobChatModel];
                        
                        //解开禁言
                        NSString *ID = jobChatModel.from == 0 ? @"" : [NSString stringWithFormat:@"%ld",jobChatModel.from];
                        [self saveReplyModelWithIsSendForbid:NO andEmployeeID:ID andMsg:@""];
                        
                        if (![[YSBCommonTool getCurrentVC] isKindOfClass:[YSBJobChatVC class]]) {//未在聊天界面需要保存到历史消息
                            LHMessageModel *messageModel = [self textModelConversionWithModel:jobChatModel];
                            NSArray *historyArr = [self catchHistoryChatRecordWithEmployeeID:ID];
                            
                            NSMutableArray *dataSource = [[NSMutableArray alloc] initWithArray:historyArr];
                            [dataSource addObject:messageModel];
                            [self saveHistoryChatRecordWithEmployeeID:ID andDataArray:[dataSource copy]];
                            
                            [self getJobChatListWithStartIndex:0 andSearchName:@""];
                        }
                        
                        
                    }
                    
  
                    //3.收到单个用户在求职聊天的招聘邀请回复消息
                    if ([msg_type isEqualToString:@"invite_res"]) {
                        NSLog(@"进入了邀请回复");
                        YSBJobChatModel *jobChatModel = [YSBJobChatModel yy_modelWithJSON:contentDict];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshJobChatRoomMessageNotification" object:jobChatModel];
                        
                        //解开禁言
                        NSString *ID = jobChatModel.from == 0 ? @"" : [NSString stringWithFormat:@"%ld",jobChatModel.from];
                        [self saveReplyModelWithIsSendForbid:NO andEmployeeID:ID andMsg:@""];
                        
                        if (![[YSBCommonTool getCurrentVC] isKindOfClass:[YSBJobChatVC class]]) {//未在聊天界面需要保存到历史消息
                            [self replaceDataWithModel:jobChatModel];
                            NSLog(@"进入未在聊天界面的离线邀请反馈");
                            [self getJobChatListWithStartIndex:0 andSearchName:@""];
                        }
                        
                    }
                    
                    
                    
                    //4.收到求职聊天的沟通回复消息
                    if ([msg_type isEqualToString:@"reply"]) {
                        NSLog(@"进入了沟通回复");
                        YSBJobChatModel *jobChatModel = [YSBJobChatModel yy_modelWithJSON:contentDict];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshJobChatRoomMessageNotification" object:jobChatModel];
                        
                        if (![[YSBCommonTool getCurrentVC] isKindOfClass:[YSBJobChatVC class]]) {//未在聊天界面需要保存到本地数据
                            if ([jobChatModel.content isEqualToString:@"reply_ok"]) {//允许聊天
                                //解开禁言
                                NSString *ID = jobChatModel.from == 0 ? @"" : [NSString stringWithFormat:@"%ld",jobChatModel.from];
                                [self saveReplyModelWithIsSendForbid:NO andEmployeeID:ID andMsg:@""];
                            }
                            else if ([jobChatModel.content isEqualToString:@"reply_no"]) {//拒绝聊天
                                //进行禁言
                                NSString *ID = jobChatModel.from == 0 ? @"" : [NSString stringWithFormat:@"%ld",jobChatModel.from];
                                [self saveReplyModelWithIsSendForbid:YES andEmployeeID:ID andMsg:@"雇员已拒绝沟通"];
                            }
                            
                            [self getJobChatListWithStartIndex:0 andSearchName:@""];
                        }
                        
                    }
                    
                    
                }
            }
            
        }
        
    }
    
}




@end




@implementation YSBHomeController

- (void)getHomeActivityNoticeData {

    if (![YSBUserDefaultsTool boolForKey:@"kIsLoginSuccess"]) {
        //没有登录
        NSUserDefaults *localSave = [NSUserDefaults standardUserDefaults];
        [localSave setObject:[NSNumber numberWithBool:YES] forKey:@"canInteractionKey"];
        [localSave synchronize];
        [[YSBMSAlertManager shareManager] showAlerts];
        return;
    }
    //显示位置，home：首页，discover：发现页 ,默认返回发现页banner列表
    NSDictionary *parameter = @{};
    [[HttpClient sharedInstance] getURL:@"https://common.ysbjob.com/v1/activity-notice/list" parameter:parameter success:^(id responseObject) {
        [self hideErrorView];
        //存入沙盒
        NSUserDefaults *localSave = [NSUserDefaults standardUserDefaults];
        [localSave setObject:[NSNumber numberWithBool:YES] forKey:@"canInteractionKey"];
        [localSave synchronize];
        
        NSNumber *code = responseObject[@"status_code"];
        if ([code intValue] == 200) {
            
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *data = responseObject[@"data"];
                
                NSArray *dataArray = [[NSArray alloc] init];
                if ([data[@"list"] isKindOfClass:[NSArray class]]) {
                    dataArray = data[@"list"];
                    NSMutableArray *tmpArr = [NSMutableArray array];
                    for (NSDictionary *d in dataArray) {
                        YSBAnnouncementModel *model = [YSBAnnouncementModel yy_modelWithJSON:d];
                        [tmpArr addObject:model];
                    }
                    if (tmpArr.count > 0) {
                        self.isCloseAdAlert = false;
                                                
                        [self performSelector:@selector(delayMethod:) withObject:[tmpArr copy] afterDelay:0];

                    }else{
                        [[YSBMSAlertManager shareManager] showAlerts];
                    }
                }else{
                    [[YSBMSAlertManager shareManager] showAlerts];
                }
            }else{
                [[YSBMSAlertManager shareManager] showAlerts];
            }
        }else{
            [[YSBMSAlertManager shareManager] showAlerts];
        }
        
    } failure:^(NSError *error) {
        [[YSBMSAlertManager shareManager] showAlerts];
        //存入沙盒
        NSUserDefaults *localSave = [NSUserDefaults standardUserDefaults];
        [localSave setObject:[NSNumber numberWithBool:YES] forKey:@"canInteractionKey"];
        [localSave synchronize];
    }];
    
}



- (void)delayMethod:(NSArray *)array {
    
    NKAlertView *alertView = [[NKAlertView alloc] init];
    YSBAnnouncementScrollView *boxView = [[YSBAnnouncementScrollView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 460) andData:array bottomButtonTitle:@"关闭" andBottomAction:^(YSBAnnouncementModel *model) {
        if (![YSBCommonTool isBlankString:model.link]) {
            YSBWebViewController *vc = [[YSBWebViewController alloc] init];
            vc.alertView = alertView;
            vc.titleStr = [YSBCommonTool isBlankString:model.title] ? @"" : model.title;
            vc.url = model.link;
            vc.isNeedStatistical = YES;
            vc.myClickBlock = ^(CGFloat time) {
                [[InterfaceSwitchingLogic defaultShareManager] uploadHomeActivityNoticeStatisticsWithActivityID:model.ID andType:@"2" andDuration:0];
                [[InterfaceSwitchingLogic defaultShareManager] uploadHomeActivityNoticeStatisticsWithActivityID:model.ID andType:@"4" andDuration:time];
            };
            UIWindow *window = [[UIApplication sharedApplication] keyWindow];
            YSBNavigationController *nav = [(YSBTabBarController *)window.rootViewController selectedViewController];
            [nav pushViewController:vc animated:YES];
        }
    } andCloseAction:^{
        [InterfaceSwitchingLogic defaultShareManager].endTime = [NSDate date];
        
        NSString *cid = [InterfaceSwitchingLogic defaultShareManager].currentID;
        NSDate *beginTime = [InterfaceSwitchingLogic defaultShareManager].beginTime;
        NSDate *endTime = [InterfaceSwitchingLogic defaultShareManager].endTime;
        
        if ([YSBCommonTool isBlankString:cid]) {
            YSBAnnouncementModel *model = array[0];
            cid = model.ID;
        }
        
        NSInteger duration = [YSBCommonTool getSecondBetweenDatesWithFirstDate:beginTime andSecondDate:endTime];
        [[InterfaceSwitchingLogic defaultShareManager] uploadHomeActivityNoticeStatisticsWithActivityID:cid andType:@"1" andDuration:0];
        [[InterfaceSwitchingLogic defaultShareManager] uploadHomeActivityNoticeStatisticsWithActivityID:cid andType:@"3" andDuration:(CGFloat)duration];
        
        self.isCloseAdAlert = true;
    }];
    boxView.switchLeftOrRightBtnBlock = ^(NSString *activityID, CGFloat duration,NSString *currentID) {
        [InterfaceSwitchingLogic defaultShareManager].beginTime = [NSDate date];
        [InterfaceSwitchingLogic defaultShareManager].currentID = currentID;
        
        [[InterfaceSwitchingLogic defaultShareManager] uploadHomeActivityNoticeStatisticsWithActivityID:activityID andType:@"1" andDuration:0];
        [[InterfaceSwitchingLogic defaultShareManager] uploadHomeActivityNoticeStatisticsWithActivityID:activityID andType:@"3" andDuration:duration];
    };
    alertView.contentView = boxView;
    //添加弹框界面
    
    if (alertView) {
        alertView.tag = 3;
        [alertView show];
        [alertView viewHidden];
        [[YSBMSAlertManager shareManager] addAlert:alertView];
    }
    [[YSBMSAlertManager shareManager] showAlerts];

    
}


@end




@implementation InterfaceSwitchingLogic


//消息栏目跳转界面逻辑
+ (void)interfaceSwitchingLogicWithModel:(YSBMessageModel *)model {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    YSBNavigationController *nav = [(YSBTabBarController *)window.rootViewController selectedViewController];
        
    //跳转界面判断,雇主端类型:1.去首页  2.去员工列表  3.订单详情  4.补工资详情  101.职位详情  102.查看报名人员  103.查看到面人员
    //雇员端:101.职位详情   105.录用详情
   switch (model.extraModel.type.integerValue) {
       case 1:{//去首页
           [nav popToViewController:[nav.viewControllers objectAtIndex:0] animated:NO];
           AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
           YSBTabBarController *tabbar = (YSBTabBarController *)appDelegate.window.rootViewController;
           [tabbar setSelectedIndex:0];
       }
           break;
       case 2:{//去员工列表
           if (model.extraModel.ID.intValue == 0) {
               return;
           }
           return;
       }
           break;
       case 3:{//订单详情
           //去查看，订单详情页
           if (model.extraModel.ID.intValue == 0) {
               return;
           }
           
           YSBOrderDetailNewViewController *vc = [[YSBOrderDetailNewViewController alloc] initWithOrderId:[model.extraModel.ID integerValue] andMId:[model.extraModel.mid integerValue] andWorkType:YSBWorkTypeTemporary andComeFromMessage:YES];
           [nav pushViewController:vc animated:YES];
       }
           break;
       case 4:{//补工资详情
           if (model.extraModel.ID.intValue == 0) {
               return;
           }
           YSBRepairWagesApplyDetailViewController *vc = [[YSBRepairWagesApplyDetailViewController alloc]init];
           YSBRepairWagesModel *rModel = [[YSBRepairWagesModel alloc] init];
           rModel.ID = [NSNumber numberWithInteger:model.extraModel.ID.integerValue];
           vc.model = rModel;
           [nav pushViewController:vc animated:YES];
       }
           break;
       case 11:{//信用账户解约失败"去查看"事件
           YSBProtocolStateViewController *vc = [[YSBProtocolStateViewController alloc] init];
           [nav pushViewController:vc animated:YES];
           
       }
           break;
       case 101:{//职位详情
           if (model.extraModel.ID.intValue == 0) {
               return;
           }
           
           YSBPermanentWorkerHomeController * vc = [[YSBPermanentWorkerHomeController alloc] init];
           vc.recruitment_id = [model.extraModel.ID integerValue];
           [nav pushViewController:vc animated:YES];

       }
           break;
       case 102:{//查看报名人员
           if (model.extraModel.ID.intValue == 0) {
               return;
           }
           YSBPermanentWorkerHomeController *vc = [[YSBPermanentWorkerHomeController alloc] init];
           vc.recruitment_id = [model.extraModel.ID integerValue];
           vc.index = 1;
           vc.status = 1;//状态 1：待面试(已报名) 2：已到面 4：已发录用通知
           [nav pushViewController:vc animated:YES];
       }
           break;
       case 103:{//查看到面人员
           if (model.extraModel.ID.intValue == 0) {
               return;
           }
           YSBPermanentWorkerHomeController *vc = [[YSBPermanentWorkerHomeController alloc] init];
           vc.recruitment_id = [model.extraModel.ID integerValue];
           vc.index = 1;
           vc.status = 2;//状态 1：待面试(已报名) 2：已到面 4：已发录用通知
           [nav pushViewController:vc animated:YES];
       }
           break;
       default:{
           if ([YSBCommonTool isBlankString:model.content]) {
               return;
           }
           YSBMessageModel *messageModel = [[YSBMessageModel alloc] init];
           messageModel.extraModel = [[ExtraModel alloc] init];
           messageModel.title = model.title;
           messageModel.extraModel.title = model.extraModel.title;
           messageModel.content = model.content;
           
           YSBMessageDetailViewController *vc = [[YSBMessageDetailViewController alloc] init];
           vc.model = messageModel;
           [nav pushViewController:vc animated:YES];
       }
           break;
   }
}


@end






@interface YSBPermanentWorkerHomeController : YSBViewController


@property (nonatomic, assign ) NSInteger recruitment_id;


@property (nonatomic, assign) NSInteger index;

@property (nonatomic, assign) NSInteger status;


@end



@implementation YSBPermanentWorkerHomeController


- (instancetype)init{
    if (self = [super init]) {
        self.selectedIndex = 0;
    }
    return self;
}


- (void)setIndex:(NSInteger)index{
    
    if (index > 0 && index <= self.VCArray.count) {
        
        self.selectedIndex = index;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"职位详情";
    
    self.segmented.selectedSegmentIndex = self.selectedIndex;
    [self.pageVC setViewControllers:@[[self.VCArray objectAtIndex:self.selectedIndex]] direction:0 animated:YES completion:nil];
    
    [self.view addSubview:self.segmented];
    [self.view addSubview:self.pageVC.view];

}


- (NSArray *)VCArray{
    
    if (!_VCArray) {
        //1.详情
        YSBPermanentWorkerRecruitmentDetailController * detailvc = [[YSBPermanentWorkerRecruitmentDetailController alloc] init];
        detailvc.employment_id = self.recruitment_id;
        
        //2.求职列表
        YSBJobListViewController * jobvc = [[YSBJobListViewController alloc] init];
        jobvc.recruitment_id = [NSString stringWithFormat:@"%ld",self.recruitment_id];
        if (self.status == 0) {
            jobvc.status = 1;
        }
        else{
            jobvc.status = self.status;
        }
        
        //3.附近的人
        YSBNearbyPersonnelViewController *nearbyVC = [[YSBNearbyPersonnelViewController alloc] init];
        
        _VCArray = @[detailvc,jobvc,nearbyVC];
    }
    
    return _VCArray;
}



@end
